﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Gateway.Configuration.Converter
{
    public class TargetRouteConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            return ((objectType == typeof(string) || objectType == typeof(List<TargetRoute>)));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<TargetRoute> collection = null;
            
            if (reader.TokenType == JsonToken.StartArray)
            {
                //deserialize array
                collection = serializer.Deserialize<List<TargetRoute>>(reader);
            }
            else
            {
                //deserialize string
                collection = new List<TargetRoute>();
                collection.Add(new TargetRoute((string)reader.Value));
            }

            return collection;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var collection = value as List<TargetRoute>;

            if (collection.Any() && collection.Count == 1 && collection.First().IsDefault)
            {
                //serialize Target as string
                var singleItem = collection.First();
                serializer.Serialize(writer, singleItem.Redirect);
            }
            else
            {
                //serialize collection
                serializer.Serialize(writer, value);
            }
        }
    }
}
